package rabbitmq.simple;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumeDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2. 创建 channel
        Channel channel = connection.createChannel();

        // 3. 声明队列
        channel.queueDeclare("hello", true, false, false, null);

        // 4. 消费消息
        /*
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数说明:
         * queue: 队列名称
         * autoAck: 是否自动确认
         * callback: 接收到消息后, 执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接受到消息: " + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);
        Thread.sleep(2000);

        // 5. 释放资源
        channel.close();
        connection.close();
    }
}
